<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'bas:route:edit'" @register="registerDrawer"
    @ok="handleSubmit" width="70%">
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span v-if="record.routeType == 0"> {{ getTitle.value }}常规工艺 </span>
      <span v-else> {{ getTitle.value }}数铣工艺 </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor v-model:value="model[field]" :bizKey="record.id" :bizType="'routeDataChild_' + field"
          :height="300" />
      </template>
      <template #operList>
        <BasicTable @register="registerRouteDataChildTable" @row-click="handleRouteDataChildRowClick">
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" style="padding: 8px">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>
        </BasicTable>
        <a-button class="mt-2" @click="handleRouteDataChildAdd" v-auth="'bas:route:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    // 当前组件名称（与路由名一致，如果不一致会页面缓存失效）
    name: 'ViewsRouteDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { routeSaveListData, Route, routeForm, operTreeData } from '/@/api/bas/route/route';
  // import { defineComponent, ref } from 'vue';
  // import useTableDraggable from '/@/hooks/component/useTableDraggable';
  // src\components\\\hooks\useTableDraggable.ts

  import { WangEditor } from '/@/components/WangEditor';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const record = ref < Route > ({} as Route);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增') : t('编辑'),
  }));
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工艺编码'),
      field: 'routeCode',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
    },
    {
      label: t('工艺名称'),
      field: 'routeName',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
    },
    {
      label: t('工艺类别'),
      field: 'routeType',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 200,
        dictType: 'bas_route_type',
      },
      required: true,
    },
    {
      label: t('工艺说明'),
      field: 'remarks',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      // required: true,
    },
    {
      label: t('工艺工序'),
      field: 'operList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'operList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,

    baseColProps: { lg: 24, md: 24 },
  });

  const [registerRouteDataChildTable, RouteDataChildTable] = useTable({
    actionColumn: {
      width: 80,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRouteDataChildDelete.bind(this, record),
          },
          auth: 'bas:route:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true, //是否显示序列号
  });

  async function setRouteDataChildTableData(_res: Recordable) {
    RouteDataChildTable.setColumns([
      {
        title: t('上移 / 下移'),
        slot: 'sortUp',
        width: 80,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operCode',
        dataLabel: 'oper.operName',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: operTreeData,
          params: {
            onlyParent: record.value.routeType == 0 ? 1 : 0,
            bsx: record.value.routeType == 1 ? 1 : 0,
          },
          canSelectParent: false,
        },
        editRule: true,
        editable: true,
      },
      // {
      //   title: t('加工时长'),
      //   dataIndex: 'jgtime',
      //   width: 50,
      //   align: 'center',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editRule: true,
      // },
      // {
      //   title: t('调试时长'),
      //   dataIndex: 'tstime',
      //   width: 50,
      //   align: 'center',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editRule: true,
      // },
      // {
      //   title: t('单价'),
      //   dataIndex: 'fprice',
      //   width: 50,
      //   align: 'center',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editRule: false,
      // },
      {
        title: t('班次数'),
        dataIndex: 'teamQty',
        width: 50,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('表面处理'),
        dataIndex: 'bmcl',
        width: 180,
        align: 'left',
        dictType: 'm8_outer_route',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'm8_outer_route',
          mode: 'multiple',
          allowClear: true,
        },
        editRule: false,
        editable: true,
        customCell: (record: Recordable) => {
          let color = ''
          color = record.oper?.bout == '1' ? '#f8d8d8' : '';
          return {
            // innerHTML: record.testTextarea, // 原样输出，不进行html编码（例子）
            style: `background-color: ${color} !important`,
          };
        },
      },
      {
        title: t('加工说明'),
        dataIndex: 'remarks',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        editable: true,
      },
    ]);
    RouteDataChildTable.setTableData(record.value.operList || []);
  }

  function handleRouteDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRouteDataChildAdd() {
    RouteDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      teamQty: '1'
    });

    // 新增的时候把数据存下来方便后面上下移动
    // addDataList.value = RouteDataChildTable.getDataSource(); // 保存当前表格数据
  }

  function handleRouteDataChildDelete(record: Recordable) {
    RouteDataChildTable.deleteTableDataRecord(record);
  }

  async function getRouteDataChildList() {
    let routeDataChildListValid = true;
    let routeDataChildList: Recordable[] = [];
    for (const record of RouteDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        routeDataChildListValid = false;
      }
      routeDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of RouteDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      routeDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!routeDataChildListValid) {
      throw { errorFields: [{ name: ['routeDataChildList'] }] };
    }
    return routeDataChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await routeForm(data);

    record.value = (res.basRoute || {}) as Route;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRouteDataChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };

      data.operList = await getRouteDataChildList();
      // console.log('submit', params, data, record);
      const res = await routeSaveListData(params, data);
      setDrawerProps({ confirmLoading: false });
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
      // let flag = true;
      // RouteDataChildTable.getDataSource().forEach((item) => {
      //   if (item.oper.bout == '1' && !item.editValueRefs?.bmcl) {
      //     flag = false;
      //   }
      // });
      // if (!flag) {
      //   showMessage(t('工序为外协时表面处理必填。'));
      // } else {
      //   data.operList = await getRouteDataChildList();
      //   // console.log('submit', params, data, record);
      //   const res = await routeSaveListData(params, data);
      //   setDrawerProps({ confirmLoading: false });
      //   showMessage(res.message);
      //   setTimeout(closeDrawer);
      //   emit('success', data);
      // }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function clickUp(record) {
    // 上移
    let arr = RouteDataChildTable.getDataSource();
    // let i = RouteDataChildTable.getSelectRowKeys();
    // index = -1,
    // for(const i=0;i<arr.length-1;i++)
    // console.table('原始数组', arr);

    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }

    if (index === 0) {
      return false;
    }

    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    RouteDataChildTable.setTableData(arr || []);
  }
  // 下移
  function clickDown(record) {
    let arr = RouteDataChildTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    RouteDataChildTable.setTableData(arr || []);
  }
</script>